// 学员信息

// 获取tbody
const tbody = document.querySelector('tbody')

// 写一个渲染函数
async function render() {
  const res = await axios.get('/student/list')
  const trArray = res.data.data.map(item => `<tr>
  <th scope="row">${item.id}</th>
  <td>${item.name}</td>
  <td>${item.age}</td>
  <td>${item.sex}</td>
  <td>${item.group}</td>
  <td>${item.phone}</td>
  <td>${item.salary}</td>
  <td>${item.truesalary}</td>
  <td>${item.province} - ${item.city} - ${item.county}</td>
  <td>
    <button class="btn btn-primary" data-type="modify" data-id="${item.id}">修改</button>
    <button class="btn btn-danger" data-type="delete" data-id="${item.id}">删除</button>
  </td>
</tr>`)
  // 渲染tbody
  tbody.innerHTML = trArray.join('')
}

// 渲染省份
async function renderProvince() {
  const res = await axios.get('geo/province')
  // 根据数据映射出选项数组
  const optionArray = res.data.map(item => `<option value="${item}">${item}</option>`)
  // 获取省份select
  const province = document.querySelector('#province')
  // 把选项option插入到省份select
  province.insertAdjacentHTML('beforeend', optionArray.join(''));
}

// 渲染城市
async function renderCity(provinceName) {
  // 加载省份的城市
  const res = await axios.get('geo/city', {
    params: { pname: provinceName }
  })
  // 把城市列表映射成option数组
  const optionArray = res.data.map(i => `<option value="${i}">${i}</option>`)
  // 在数组头部增加一个默认选项
  optionArray.unshift('<option selected>--市--</option>')
  //  获取城市select
  const city = document.querySelector('#city')
  city.innerHTML = optionArray.join('')
}

// 渲染县
async function renderCounty(provinceName, cityName) {
  const res = await axios.get('geo/county', {
    params: {
      pname: provinceName,
      cname: cityName,
    }
  })
  // 获取县select
  const county = document.querySelector('#county')
  const optionArray = res.data.map(item => `<option value="${item}">${item}</option>`)
  // 数组在头部插入内容
  optionArray.unshift('<option selected>--县--</option>')
  county.innerHTML = optionArray.join('')
}

// 获取省份，监听切换事件：change
const province = document.querySelector('#province')
province.addEventListener('change', async () => {
  const name = province.value
  if (name !== '--省--') {
    renderCity(name)
  }
})

const city = document.querySelector('#city')
city.addEventListener('change', () => {
  const name = city.value;
  if (name !== '--市--') {
    renderCounty(province.value, name)
  }
})

// 第一次渲染
render()
// 渲染省份
renderProvince()
// 获取表单
const form = document.querySelector('#studentForm')
// 获取弹窗的保存按钮，绑定点击事件
const saveBtn = document.querySelector('#saveBtn')
saveBtn.addEventListener('click', async () => {

  // 创建一个FormData
  const fd = new FormData(form)

  // 把fd转换为对象
  const object = Array.from(fd).reduce((acc, [key, value]) => {
    acc[key] = value;
    return acc
  }, {});
  //解构id
  const { id } = saveBtn.dataset;
  //判断是新增还是添加
  if (id) {
    //编辑
    object.id = id
    //调用接口
    await axios.put('student/update', object)
  } else {
    // 调用接口
    await axios.post('student/add', object)
  }

  toastr.success('添加成功')
  // 提交结束隐藏弹窗
  const modal = bootstrap.Modal.getOrCreateInstance('#exampleModal')
  modal.hide()
})

//获取新增表单学员按钮，绑定点击
const addBtn = document.querySelector('#addStudent')
addBtn.addEventListener('click', () => {
  //重置表单
  form.reset()
  //重置id
  saveBtn.dataset.id = ''
  //控制弹窗
  updateModalText('录入新学员', '确认添加')

  const modal = bootstrap.Modal.getOrCreateInstance('#exampleModal')
  modal.show()
})
//修改弹窗内容
function updateModalText(title, btn) {
  document.querySelector('#exampleModalLabel').innerText = title
  document.querySelector('#saveBtn').innerText = btn
}
//封装函数修改输入框
function updateModalInput(name, value) {
  const input = form.querySelector(`[name=${name}]`)
  input.value = value
}
//获取重置按钮，绑定点击事件
document
  .querySelector('#resetBtn')
  .addEventListener('click', () => form.reset())
tbody.addEventListener('click', async ({ target }) => {
  const { type, id } = target.dataset

  //判断是修改
  if (type === 'modify') {
    const res = await axios.get('student/one', {
      params: {
        id,
      }
    })
    //把id饭进保存按钮
    saveBtn.dataset.id = id
    const modifyObj = res.data.data
    //遍历循环
    await renderCity(modifyObj.province)
    await renderCounty(modifyObj.province, modifyObj.city)
    for (const k in modifyObj) {
      if (k !== 'id' && k !== 'user_id' && k !== 'jing' && k !== 'wei') {
        updateModalInput(`${k}`, modifyObj[k])
      }
    }
    const radios = form.querySelectorAll('input[type=radio')
    const array = [...radios]
    const radio = array.find(radio => radio.value === modifyObj.sex)
    radio.checkeed = true
    // updateModalInput('xes', radio)

    const modal = bootstrap.Modal.getOrCreateInstance('#exampleModal')
    modal.show()
    updateModalText('修改学员', '保存修改')
  } else if (type === 'delete') {
    if (confirm(`What's a dogs name?`)) {
      await axios.delete('student/delete', {
        params: {
          id,
        }
      })
      //提示用户
      toastr.success('删除成功')
      //重新渲染
      render()
    }
  }
})